package com.fresh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fresh.entity.FreshGoods;
import com.fresh.mapper.GoodsMapper;
import com.fresh.qo.GoodsQO;
import com.fresh.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, FreshGoods> implements GoodsService {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private RedisTemplate strRedisTemplate;

    @Override
    public List<FreshGoods> getAll() {
        List<FreshGoods> freshGoodsList = goodsMapper.selectAll();
        return freshGoodsList;
    }


    @Override
    public IPage<FreshGoods> getByConditionAndPage(GoodsQO goodsQO) {
        //TODO 条件查询
        QueryWrapper<FreshGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(goodsQO.getName()), "name", goodsQO.getName())
                .eq(!StringUtils.isEmpty(goodsQO.getUnitId()), "unit_id", goodsQO.getUnitId())
                .eq(!StringUtils.isEmpty(goodsQO.getCategoryId()), "category_id", goodsQO.getCategoryId())
                .eq(!StringUtils.isEmpty(goodsQO.getSupplierId()), "supplier_id", goodsQO.getSupplierId())
                .ge(!StringUtils.isEmpty(goodsQO.getMaxUpdateTime()), "update_time", goodsQO.getMaxUpdateTime())
                .le(!StringUtils.isEmpty(goodsQO.getMinUpdateTime()), "update_time", goodsQO.getMinUpdateTime())
                .ge(!StringUtils.isEmpty(goodsQO.getMaxPrice()), "price", goodsQO.getMaxPrice())
                .le(!StringUtils.isEmpty(goodsQO.getMinPrice()), "price", goodsQO.getMinPrice())
                .eq(!StringUtils.isEmpty(goodsQO.getType()), "type", goodsQO.getType());
        //TODO 分页查询
        Page<FreshGoods> goodsPage = new Page<>(goodsQO.getPageNum(), goodsQO.getPageSize());
        IPage<FreshGoods> goodsIPage = goodsMapper.selectPage(goodsPage, queryWrapper);
        return goodsIPage;
    }

    @Override
    public FreshGoods selectById(Long goodsId) {
        return goodsMapper.selectById(goodsId);
    }

    @Override
    public void updateById(Long goodsId, Integer stock) {
        goodsMapper.updateById(goodsId,stock);
    }

    @Override
    public void initGoodsInRedis(Integer goodsId, Integer stock) {
        for (int i = 1; i <= stock; i++) {
            strRedisTemplate.opsForList().leftPush("goodsKill::"+goodsId.toString(),i);
        }
    }

    @Override
    public void importDataToDB(FreshGoods freshGoods) {
        goodsMapper.add(freshGoods);
    }

}
